import { useGlobalState } from '@/hooks';
import Link from 'next/link';
import { MouseEventHandler, useEffect, useRef, useState } from 'react';

const rootId = Number(process.env.NEXT_PUBLIC_ROOT_CATEGORY_ID);

const getCategoryLink = (cat: Obj | null, categories: any[] | null) => {
  let currCat = { ...cat };
  if (!currCat.url_key) return '';
  const pathArray = [currCat.url_key];
  while (currCat?.parent_id && currCat?.parent_id != rootId) {
    currCat = categories?.find(c => c.category_id == currCat.parent_id);
    if (currCat) pathArray.push(currCat.url_key);
  }
  return '/categories/' + pathArray.reverse().join('/');
};
const getChildrens = (pid: any, categories: any[] | null) => {
  if (!pid) return null;
  return categories?.filter((d: any) => d.parent_id == pid);
};

const SecondCategoryCard = ({
  category,
  childrens,
  categories,
  overId,
  onOver,
}: {
  category: any;
  childrens?: any[] | null;
  categories: any[] | null;
  overId?: string;
  onOver?: MouseEventHandler;
}) => {
  const cardRef = useRef<any>(null);
  useEffect(() => {
    if (cardRef.current) {
      const rows = Math.ceil(cardRef.current?.clientHeight / 5) + 2;
      cardRef.current.style.gridRowEnd = `span ${rows}`;
    }
  }, [cardRef, childrens]);
  return (
    <div className="category-block" ref={cardRef}>
      <div
        onMouseOver={onOver}
        data-category_id={category.category_id}
        data-parent_id={category.parent_id}
        data-title={category.title}
        className={
          'category-item ' + (overId == category.category_id && 'active')
        }
      >
        <Link href={getCategoryLink(category, categories)}>
          {category.title}
        </Link>
      </div>
      {childrens?.map((ca3: any, index) => (
        <div
          key={index}
          onMouseOver={onOver}
          data-category_id={ca3.category_id}
          data-parent_id={ca3.parent_id}
          data-title={ca3.title}
          className={
            'category-item sub ' + (overId == ca3.category_id && 'active')
          }
        >
          <Link href={getCategoryLink(ca3, categories)}>{ca3.title}</Link>
        </div>
      ))}
    </div>
  );
};

const CategoriesSub = ({
  hoverCategory1,
  // hoverCategory2,
  // handleItemOverAll,
  // handleItemOver2,
  categories,
}: {
  hoverCategory1: Obj | null;
  // hoverCategory2: Obj | null;
  // handleItemOverAll: Fn;
  // handleItemOver2: Fn;
  categories: any[] | null;
}) => {
  const [hoverCategory2, seHoverCategory2] = useState<any>(null);
  const handleItemOver2 = (e: any) => {
    if (e.currentTarget?.dataset?.category_id) {
      const cat = e.currentTarget?.dataset;
      seHoverCategory2({ ...cat });
    }
  };
  const handleItemOverAll = (e: any) => {
    seHoverCategory2(null);
  };
  useEffect(() => {
    seHoverCategory2(null);
  }, [hoverCategory1]);
  // console.log('############# init SUB categories #############');

  return (
    <div className="main-menu-category-level-2-wrapper">
      <div
        className="main-menu-category-level2-all"
        data-category_id={hoverCategory1?.category_id}
        data-parent_id={hoverCategory1?.parent_id}
        data-title={hoverCategory1?.title}
      >
        <Link href={getCategoryLink(hoverCategory1, categories)}>
          <span className="category-all-item" onMouseOver={handleItemOverAll}>
            Shop All {hoverCategory1?.title}
          </span>
        </Link>
      </div>
      <div className="main-menu-category-level-2-list">
        {getChildrens(hoverCategory1?.category_id, categories)?.map(
          (ca2: any, index: number) => (
            <SecondCategoryCard
              key={index}
              category={ca2}
              categories={categories}
              childrens={getChildrens(ca2.category_id, categories)}
              overId={hoverCategory2?.category_id}
              onOver={handleItemOver2}
            />
          )
        )}
      </div>
    </div>
  );
};

export default CategoriesSub;
